//
//  FDMMasterDetailViewController.m
//  Entertainment
//
//  Created by dllo on 16/4/23.
//  Copyright © 2016年 付冬梅. All rights reserved.
//

#import "FDMMasterDetailViewController.h"
#import "FDMMasterCollectionReusableViewInfo.h"
#import "FDMMasterCollectionViewCellTrack.h"
#import "FDMMasterCollectionReusableViewTrack.h"
#import "FDMMasterCollectionViewCellVoice.h"
#import "FDMMasterTrackModel.h"
#import "FDMMasterVoiceModel.h"

@interface FDMMasterDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, BackDelegate, ShareDelegate, DownDelegate, FllowingsDelegate>

@property (nonatomic, retain) FDMBaseCollectionView *collectionView;
@property (nonatomic, retain) NSMutableDictionary *masterInformationDic;/**< 主播信息 */
@property (nonatomic, retain) NSMutableArray *trackListModelArr;/**< 发布的专辑 */
@property (nonatomic, retain) NSMutableArray *voiceModelArr;/**< 发布的声音 */

@property (nonatomic, assign) BOOL isRefresh;/**< 记录刷新状态 */
@property (nonatomic, assign) NSInteger page;/**< 记录页码 */

@end
@implementation FDMMasterDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self addLeftAndRightItem];
    
    // 创建
    [self createCollectionView];
    // 数据
    [self dataHandel];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = YES;
    
    // 初始化
    self.masterInformationDic = [NSMutableDictionary dictionary];
    self.trackListModelArr = [NSMutableArray array];
    self.voiceModelArr = [NSMutableArray array];
    
    // 下拉刷新
    [self addHeader];
    // 上拉加载
    [self addFooter];
    self.page = 1;
}

//- (void)addLeftAndRightItem {
//    UIButton *leftBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    leftBackButton.frame = CGRectMake(20, 20, 40, 40);
//    [leftBackButton setImage:[UIImage imageNamed:@"find_album_play@2x.png"] forState:UIControlStateNormal];
//    leftBackButton.backgroundColor = [UIColor whiteColor];
//    [leftBackButton addTarget:self action:@selector(leftBackButton:) forControlEvents:UIControlEventTouchUpInside];
////    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBackButton];
////    self.navigationItem.rightBarButtonItem = leftBarButtonItem;
//    [self.view addSubview:leftBackButton];
//    
//}

- (void)leftBackButton:(UIButton *)button {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)addHeader {

    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isRefresh = YES;
        [self dataHandel];
    }];
}

- (void)addFooter {
    
    
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _page++;
        [self dataHandel];
        self.isRefresh = NO;
    }];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[FDMBaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[FDMMasterCollectionReusableViewInfo class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FDMMasterCollectionReusableViewInfo"];
    [self.collectionView registerClass:[FDMMasterCollectionReusableViewTrack class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FDMMasterCollectionReusableViewTrack"];
    [self.collectionView registerClass:[FDMMasterCollectionViewCellTrack class] forCellWithReuseIdentifier:@"FDMMasterCollectionViewCellTrack"];
    [self.collectionView registerClass:[FDMMasterCollectionViewCellVoice class] forCellWithReuseIdentifier:@"FDMMasterCollectionViewCellVoice"];
}

#pragma mark - collectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 320);
    }
    if (section == 1) {
        return CGSizeMake(SCREEN_WIDTH, 30);
    } else {
        return CGSizeMake(SCREEN_WIDTH, 30);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeZero;
    }
    if (indexPath.section == 1) {
        return CGSizeMake(SCREEN_WIDTH - 20, 100);
    } else {
        return CGSizeMake(SCREEN_WIDTH - 20, 100);
    }

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 1) {
        return self.trackListModelArr.count;
    }
    if (section == 2) {
        return self.voiceModelArr.count;
    } else {
        return 0;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (kind == UICollectionElementKindSectionHeader) {
            FDMMasterCollectionReusableViewInfo *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FDMMasterCollectionReusableViewInfo" forIndexPath:indexPath];
            
            if (self.masterInformationDic.allKeys.count) {
                header.headerDic = self.masterInformationDic.mutableCopy;
                header.headerImage = self.headerImage;
            }
            header.backDelegate = self;
            header.shareDelegate = self;
            header.downDelegate = self;
            header.followingsDelegate = self;
            return header;
        }

    } else {
        if (kind == UICollectionElementKindSectionHeader) {
            FDMMasterCollectionReusableViewTrack *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FDMMasterCollectionReusableViewTrack" forIndexPath:indexPath];
            if (indexPath.section == 1) {
                header.titleLabel.text = [NSString stringWithFormat:@"发布的专辑"];
            }
            if (indexPath.section == 2) {
                header.titleLabel.text = @"发布的声音";
            }
            header.backgroundColor = [UIColor colorWithRed:0.80 green:0.80 blue:0.80 alpha:1.00];
            return header;
        }
    }
        return nil;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        FDMMasterCollectionViewCellTrack *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMMasterCollectionViewCellTrack" forIndexPath:indexPath];
        if (self.trackListModelArr.count) {
            FDMMasterTrackModel *model = self.trackListModelArr[indexPath.row];
            cell.trackModel = model;
        }
        
        return cell;
    }
    if (indexPath.section == 2) {
        FDMMasterCollectionViewCellVoice *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FDMMasterCollectionViewCellVoice" forIndexPath:indexPath];
        FDMMasterVoiceModel *model = self.voiceModelArr[indexPath.row];
        if (self.voiceModelArr.count) {
            cell.voiceModel = model;
        }
        return cell;
    }
    return nil;
    
}

- (void)dataHandel {
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/homePage?device=android&statEvent=pageview/user@%@&statModule=热门&statPage=tab@发现_主播&statPosition=1&toUid=%@", self.uid, self.uid];
    NSString *str3 = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%@/%ld/30?count=30&device=android&page=%ld&track_base_url=http://mobile.ximalaya.com/mobile/others/ca/track&uid=%@", self.uid, self.page, self.page, self.uid];
    NSString *str2 = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/%@/1/2?device=android&title=null", self.uid];

    [APPTools GETWithURL:str par:nil success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        if (self.isRefresh == YES) {
            
            [self.masterInformationDic removeAllObjects];
        }
        self.masterInformationDic = dic.mutableCopy;
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
        
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    [APPTools GETWithURL:str2 par:nil success:^(id responseObject) {
        NSArray *arr = responseObject[@"list"];
        if (self.isRefresh == YES) {
            [self.trackListModelArr removeAllObjects];
        }
        self.trackListModelArr = [FDMMasterTrackModel baseModelHandelWithArray:arr];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    [APPTools GETWithURL:str3 par:nil success:^(id responseObject) {
        NSArray *arr = responseObject[@"list"];
        for (NSDictionary *dic in arr) {
            FDMMasterVoiceModel *model = [[FDMMasterVoiceModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.voiceModelArr addObject:model];
        }
        [self.collectionView.mj_footer endRefreshing];
        [self.collectionView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

#pragma mark - 实现协议方法
- (void)clickBackButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickShareButton {
    NSLog(@"分享");
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]) {
        NSLog(@"服务器可用");
        
    } else {
        NSLog(@"服务器不可用");
    }
    
    SLComposeViewController *vc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeSinaWeibo];
    
    [vc addImage:[UIImage imageNamed:@""]];
    [vc addURL:[NSURL URLWithString:@""]];
    [vc setInitialText:@""];
    
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    
    // 监听分享状态
    vc.completionHandler = ^(SLComposeViewControllerResult result) {
        if (result == SLComposeViewControllerResultCancelled) {
            NSLog(@"取消发送");
        } else {
            NSLog(@"发送成功");
        }
    };
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    
    
}

- (void)clickDownButton {
    
}

- (void)clickFllowingsButton {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
